import { ApiResponse } from '@/types/data';
import { ArticleResults, RootThunkAction, SearchAction, Suggestion } from '@/types/store'
import http from '@/utils/http'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage';


export function getSuggestion(value: string): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<{ options: Suggestion }>>('/suggestion', {
      params: {
        q: value
      }
    })
    // console.log(res);
    dispatch({
      type: 'search/suggestion',
      payload: res.data.data.options
    })
  }
}

export function saveHistory(keyword: string): RootThunkAction {
  return async (dispatch, getState) => {
    // 获取到原来的histories
    let histories = getState().search.histories.filter(item => item !== keyword)
    // 1. 不允许有重复的历史记录, 先删除原来历史记录中的keyword
    // 添加keyword

    console.log(histories, keyword);
    histories = [keyword, ...histories]
    console.log(histories, keyword);


    // 最多显示10条
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    // 保存 redux
    dispatch({
      type: 'search/saveHistories',
      payload: histories,
    })
    // 保存到本地
    setLocalHistories(histories)
  }
}

/**
 * 清空历史记录
 * @returns
 */
export function clearHistories(): RootThunkAction {
  return async (dispatch) => {
    // 清空本地历史记录
    removeLocalHistories()
    // 清空redux数据
    dispatch({
      type: 'search/clearHistories',
    })
  }
}

/**
 * 删除单个历史记录
 * @returns
 */
export function deleteHisory(value: string): RootThunkAction {
  return async (dispatch, getState) => {
    let histories = getState().search.histories.filter(item => item !== value)
    // 重置本地历史记录
    setLocalHistories(histories)
    // 清空redux数据
    dispatch({
      type: 'search/replaceHistories',
      payload: histories
    })
  }
}

/**
 * 获取搜索结果数据
 */
export function getSearchResults(
  keyword: string,
  page: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<ArticleResults>>('search', {
      params: {
        q: keyword,
        page,
        per_page: 10,
      },
    })
    console.log(res.data.data);

    dispatch({
      type: 'search/saveResults',
      payload: res.data.data.results,
    })
  }
}

export function clearArticle(): SearchAction {
  return {
    type: 'search/clearArticle'
  }
}